package com.huafv.flyauth.web.admin.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huafv.flyauth.core.domain.Result;
import com.huafv.flyauth.core.domain.TreeNode;
import com.huafv.flyauth.web.admin.entity.SysMenu;
import com.huafv.flyauth.web.admin.entity.SysRole;
import com.huafv.flyauth.web.admin.entity.SysRoleMenu;
import com.huafv.flyauth.web.admin.entity.SysUserRole;
import com.huafv.flyauth.web.admin.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/system/role")
public class SysRoleController extends BaseController {

    @Autowired
    private  SysRoleService sysRoleService;

    @Autowired
    SysMenuService sysMenuService;

    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @PreAuthorize("hasAuthority('role:info')")
    @GetMapping("/info/{roleId}") // OK
    public Result info(@PathVariable(name = "roleId")Long roleId) {
        SysRole roleInfo = sysRoleService.getById(roleId);
        return Result.success(roleInfo);
    }


    @PreAuthorize("hasAuthority('role:list')")
    @GetMapping("/list")
    public Result list(String value) {

        Page<SysRole> pageData = sysRoleService.page(getPage(),
                new QueryWrapper<SysRole>()
                        .like(StrUtil.isNotBlank(value), "name", value)
                );

        return Result.success(pageData);
    }

    @PreAuthorize("hasAuthority('role:save')")
    @PostMapping("/save")
    public Result save(@Validated @RequestBody SysRole sysRole) {
        sysRole.setCreated(LocalDateTime.now());
        sysRole.setState(1);
        sysRoleService.save(sysRole);
        return Result.success(sysRole);
    }

    @PreAuthorize("hasAuthority('role:edit')")
    @PutMapping("/update")
    public Result update(@Validated @RequestBody SysRole sysRole) {

        sysRole.setUpdated(LocalDateTime.now());
        sysRoleService.updateById(sysRole);

        return Result.success(sysRole);
    }

    @PreAuthorize("hasAuthority('role:perms:edit')")
    @PutMapping("/perms/{roleId}")
    public Result updateRolePermissions(@PathVariable Long roleId, @RequestBody List<Long> menuIds) {
        // 参数验证
        if (roleId == null) {
            return Result.error("roleId不能为空");
        }
        if (menuIds == null || menuIds.isEmpty()) {
            return Result.error("menuIds不能为空");
        }

        // 构建SysRoleMenu对象列表
        List<SysRoleMenu> roleMenus = new ArrayList<>();
        for (Long menuId : menuIds) {
            SysRoleMenu roleMenu = new SysRoleMenu();
            roleMenu.setRoleId(roleId);
            roleMenu.setMenuId(menuId);
            roleMenus.add(roleMenu);
        }

        // 删除原来的角色权限记录，保存新的角色权限记录
        try {
            sysRoleMenuService.updateRoleMenus(roleId, roleMenus);
            return Result.success(null);
        } catch (Exception e) {
            return Result.error("更新角色权限失败：" + e.getMessage());
        }

        // TODO 从Redis中更新 LoginUser Perms
    }

    @PreAuthorize("hasAuthority('role:perms:info')")
    @GetMapping("/perms/{roleId}")
    public Result delete(@PathVariable(name = "roleId")Long roleId) {
        if (roleId == null) {
            // 如果角色不存在，则返回错误信息
            return Result.error("角色不存在");
        }
        // 查询角色的菜单列表
        List<SysRoleMenu> sysRoleMenus = sysRoleMenuService.list(new QueryWrapper<SysRoleMenu>().eq("role_id", roleId));
        List<Long> menuIds = new ArrayList<>();
        for (SysRoleMenu sysRoleMenu : sysRoleMenus) {
            menuIds.add(sysRoleMenu.getMenuId());
        }

        return Result.success(menuIds);
    }

    @PreAuthorize("hasAuthority('role:perms:tree')")
    @GetMapping("/perms") // OK
    public Result PermsTree() {
        List<TreeNode> treeNodes = sysMenuService.allMenusTreeNode();
        return Result.success(treeNodes);
    }
}
